package co.fitstart.mobile.web.controller.course;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.support.HttpResult;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.mobile.handler.DistanceHandler;
import co.fitstart.mobile.service.CourseScheduleService;
import co.fitstart.mobile.service.UserService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;
import co.fitstart.mobile.web.interceptor.WechatAuthority;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/profile")
public class CourseEditController {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseEditController.class);
    
    @Autowired
    private CourseScheduleService courseScheduleService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DistanceHandler distanceHandler;
    
    /**
     * View cancel course schedule panel
     * 
     * @param scheduleId
     * @return
     */
    @RequestMapping(value = "/course-schedules/{scheduleId}/cancel", method = RequestMethod.GET)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView cancelSchedule(@PathVariable("scheduleId") Long scheduleId) {
        
        ModelAndView modelAndView = new ModelAndView("course/course-schedule-cancel");
        
        CourseSchedule courseSchedule = courseScheduleService.loadCourseSchedule(scheduleId);
        modelAndView.addObject("courseSchedule", courseSchedule);
        
        return modelAndView;
    }

    /**
     * Do cancel courseSchedule 
     * 
     * @param scheduleId
     * @return
     */
    @RequestMapping(value = "/course-schedules/{scheduleId}/cancel", method = RequestMethod.PATCH)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String onCancelSchedule(@PathVariable("scheduleId") Long scheduleId) {
        
        Result result = new Result();
        
        try {
            
            CourseSchedule courseSchedule = courseScheduleService.loadCourseSchedule(scheduleId);
            
            courseScheduleService.cancelSchedule(courseSchedule);
            
            result.success().message("取消课程预约成功");
            
        } catch (Exception e) {
            
            logger.error("#onCancelSchedule() course schedule error", e);
            result.fail().message("取消课程预约失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/course-schedules/{scheduleId}/qrcode", method = RequestMethod.POST)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String generateScheduleQrcode(@Secure User user,
                                                       @PathVariable("scheduleId") Long scheduleId,
                                                       @RequestParam(value = "longitude", required = false) Double longitude,
                                                       @RequestParam(value = "latitude", required = false) Double latitude,
                                                       @RequestParam(value = "debug", required =false) boolean debug) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            logger.info("#generateScheduleQrcode with params longitude[{}] latitude[{}]", longitude, latitude);
            
            Student student = userService.getStudent(user);
            
            CourseSchedule courseSchedule = courseScheduleService.loadCourseSchedule(scheduleId);
            
            // check student and schedule
            if(student == null || !courseSchedule.matches(student)) {
                httpResult.fail().message("课程信息与用户信息不匹配");
                return JsonUtils.toJsonString(httpResult);
            }
            
            // check distance
            Site site = courseSchedule.getSite();
            
         // prepare signin qrcode if needed
            if(courseSchedule.getScheduleStatus().isReady()) {
                
                if(longitude != null & latitude != null) {
                    int distance = distanceHandler.getDistance(longitude, latitude, site.getLongitude(), site.getLatitude());
                    
                    if(distance > 2000) {
                        if(debug != true) {
                            httpResult.fail().message("请在门店1000m范围内打开");
                            return JsonUtils.toJsonString(httpResult);
                        }
                    }
                    
                    String qrCodeKey = courseScheduleService.generateScheduleQrCode(courseSchedule, true);
                    httpResult.success().data("qrcode", qrCodeKey);
                    
                } else {
                    logger.error("#generateScheduleQrcode warnings: generate this qrcode without longitude[{}] latitude[{}]", longitude, latitude);
                    
                    String qrCodeKey = courseScheduleService.generateScheduleQrCode(courseSchedule, false);
                    httpResult.success().data("qrcode", qrCodeKey);
                }
                
                
            } else {
                httpResult.fail().message("课程已签到");
            }
            
        } catch (Exception e) {
            
            logger.error("#generateScheduleQrcode() course schedule generate qrcode failed", e);
            httpResult.fail().message("生成签到二维码失败");
            
        }
        
        return JsonUtils.toJsonString(httpResult);
    }
}
